package com.huawei.M01.iterator.july;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 功能：
 *
 * @author zhiwu
 * @Data 2023/7/11 1:00
 */
public class Caculate2 {
    public int calculate(String s) {
        s = s + " ";
        StringBuilder number = new StringBuilder();
        List<String> tokens = new ArrayList<>();
        Stack<Character> opr = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            // 处理数字
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                number.append(s.charAt(i));
                continue;
            } else  {
                if (!number.toString().equals("")) {
                    tokens.add(number.toString());
                    number = new StringBuilder();
                }
            }
            // 处理空格
            if (s.charAt(i) == ' ') {
                continue;
            }
            if (opr.empty()) {
                opr.push(s.charAt(i));
            } else {
                // 处理符号
                int rkDegree = getRkDegree(s.charAt(i));
                while (!opr.empty() && rkDegree <= getRkDegree(opr.peek())) {
                    tokens.add(String.valueOf(opr.pop()));
                }
                opr.push(s.charAt(i));
            }

        }
        while (!opr.empty()) {
            tokens.add(String.valueOf(opr.pop()));
        }
        return evalRPN(tokens.toArray(new String[0]));
    }

    private int getRkDegree(char charAt) {

        if (charAt == '+' || charAt == '-') {
            return 1;
        }
        return 2;

    }

    public int evalRPN(String[] tokens) {
        // 使用栈进行处理
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
                int y = stack.pop();
                int x = stack.pop();
                stack.push(getResult(x, y, token));
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.peek();

    }

    private int getResult(int x, int y, String token) {
        if (token.equals("+")) {
            return x + y;
        }
        if (token.equals("-")) {
            return x - y;
        }
        if (token.equals("*")) {
            return x * y;
        }
        if (token.equals("/")) {
            return x / y;
        }

        return 0;
    }

    public static void main(String[] args) {
        System.out.println(new Caculate2().calculate(" 3/2 "));
    }
}
